--
-- Author: songjianbang
-- Date: 2018-8-13 
--
-- RewardCarnivalPanel
local RewardNodeRender = import(".renders.RewardNodeRender")
local IconRender = require("app.widget.renders.IconRender")
local RewardView = require("app.system.secret.SecretRewardView")
local Task = require("app.public.dao.Task")

local RewardCarnivalPanel = app.mvc.createPanelClass(...)
local Res = {
	RewardCarnivalNode = "ui2/activity/Node_carnival.csb",
	RewardCarnivalListNode = "ui2/activity/Node_list.csb",
}

--data = 
function RewardCarnivalPanel.create(data, node)
	local sprite = RewardCarnivalPanel.extend(node or cc.CSLoader:createNode(Res.RewardFameNode))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init(data)

	return sprite
end       

function RewardCarnivalPanel:init(data)
	self.super.init(self, data)

	self:setNodeEventEnabled(true)
	
	local rm = app:getInst("RewardModel")
	local m = rm:getCarnivalModel()

	self.model = m

	self.model:newReqInfo()

	self.dayListView = ccui.ListView:create()
	-- self.dayListView:setLayoutType(ccui.LayoutType.HORIZONTAL)
	self.dayListView:setDirection(ccui.ScrollViewDir.horizontal)
	-- self.dayListView:setBackGroundColorType(1)
	self.dayListView:setItemsMargin(40)
	-- self.dayListView:setBackGroundColor(cc.c3b(78, 78, 78))

	self.dayPanel = self:findChild("Panel/Panel_data/Panel_btn/bg")
	self.dayPanel:addChild(self.dayListView)
	self.dayListView:setContentSize(self.dayPanel:getContentSize())

	local act = cca.seq({cca.delay(30), cca.callFunc(function()
        self:refreshTimeString()
	end)})
	cca.repeatForever(act)
	self.dayPanel:stopAllActions()
    self.dayPanel:runAction(act)

	self.nameTemplete = self:findChild("Panel/Panel_data/Panel_btn/name_1"):clone()
	self.templete = self:findChild("Panel/Panel_data/Panel_btn/Button_1"):clone()

	self:findChild("Panel/Panel_left/tlt"):setString(L"activityname_3001")
	

	for i = 1, 5 do 
		self:findChild("Panel/Panel_data/Panel_btn/Button_"..tostring(i)):hide()
		self:findChild("Panel/Panel_data/Panel_btn/name_"..tostring(i)):hide()
	end
	
	self.nameTemplete:hide()
	self.templete:hide()

	local lastDayButton = nil
	local lastDayText = nil
	local function getDayBtn(idx)
		local p = ccui.Layout:create()
		local n = self.nameTemplete:clone()
		local b = self.templete:clone()

		if idx == self.model:getCurDay() then
			b:setTouchEnabled(false)
			b:setBright(false)
			lastDayButton = b
			lastDayText = n
		end
		

		b:setPressedActionEnabled(false)

		b:addChild(n)
		n:setString(string.format(L("lua_code_text_485"), tostring(idx)))

		local sz = b:getContentSize()
		n:setPosition(cc.p(sz.width*0.5, sz.height*0.5 - 5))

		n:show()
		b:show()

		p:setContentSize(sz)
		p:setAnchorPoint(cc.p(0.5, 0.5))
		p:addChild(b)
		b:setPosition(cc.p(sz.width*0.5, sz.height*0.5 + 3))

		local normalColor = cc.c3b(47, 12, 4)
		local selectColor = cc.c3b(255, 232, 122)

		n:setTextColor(normalColor)

		p.select = function()
			if idx > self.model:getCurDay() then
				display.pushToast( L("carnivaltips1") )
				return
			end
			n:setTextColor(selectColor)
			if lastDayButton and lastDayButton ~= b then
				self:refreshList(idx)

				b:setTouchEnabled(false)
				b:setBright(false)				

				lastDayButton:setTouchEnabled(true)
				lastDayButton:setBright(true)
				lastDayText:setTextColor(normalColor)

				lastDayButton = b	
				lastDayText = n 			
			end
			if idx > 5 then
				self.dayListView:jumpToPercentHorizontal(100)
			end
		end

		b:addClickEventListener(function(sender)        
			p.select()
		end)

		return p
	end
	local function getMargin()
		local l = ccui.Layout:create()
		l:setContentSize(cc.size(10, 10))
		return l
	end
	
	self.dayListView:pushBackCustomItem(getMargin())
	self.dayBtns = {}
	for i = 1, self.model.dayCount do
		table.insert(self.dayBtns, getDayBtn(i))
		self.dayListView:pushBackCustomItem(self.dayBtns[i])
	end
	self.dayListView:pushBackCustomItem(getMargin())	

	self.taskListView = self:findChild("Panel/Panel_data/ListView")
	self.taskListView:setDirection(ccui.ScrollViewDir.vertical)

	self.rewards = {}
	for i = 1, 5 do
		local c = RewardNodeRender.create(nil, self:findChild("Panel/Panel_bom/reward_"..tostring(i)))
		c:setVisible(false)
		c:onGetRewardClick(function(aID) self.model:reqGetAward(aID) end)		
		table.insert(self.rewards, c)
	end
	
	self:refresh()

	EM:on(self.model:getRewardsChangeEventName(), function(evt, rId)
		self:refresh()
    end)
end

function RewardCarnivalPanel:onExit()
	self.model:refreshRedPoint()
	EM:removeByName(self.model:getRewardsChangeEventName())
end

function RewardCarnivalPanel:refreshDayRedPoint()
	local c = self.model:getCurDay()
	local b = false
	for i = 1, self.model.dayCount do
		if i <= c then
			b = self.model:dayRedPoint(i)		
		else
			b = false
		end
		self:findChild("Panel/Panel_data/Panel_btn/dot_"..tostring(i)):setVisible(b)		
	end
	
	self.model:refreshRedPoint()
end

function RewardCarnivalPanel:refreshTimeString()
	local endTime = self.model.endTime - (app.session:getServerTime() - checknumber(self.model.endTimeStamp))
	local day = 0
	local hour = 0
	local minit = 0
	minit = math.ceil(endTime/60)
	hour = math.floor(math.fmod(endTime, 3600*24) / 3600)
	day = math.floor(endTime / (3600*24))

	if day > 0 then
		
		self:findChild("Panel/Panel_left/tips"):setString(string.format(L("lua_code_text_261"), tostring(day), tostring(hour)))
	else
		if hour > 0 then
			self:findChild("Panel/Panel_left/tips"):setString(string.format(L("lua_code_text_366"), tostring(hour)))
		else
			self:findChild("Panel/Panel_left/tips"):setString(string.format(L("lua_code_text_14"), tostring(minit)))
		end
	end

	if endTime <= 0 then
		self:findChild("Panel/Panel_left/tips"):setString(L("lua_code_text_361"))
	end
end

function RewardCarnivalPanel:refreshList(dayIndex)
	if dayIndex then
		self.currentDay = dayIndex
	else
		dayIndex = self.currentDay
	end

	local tasks = self.model:getTasksByDay(dayIndex)
	if tasks then
		local taskArray = string.split(tasks, ";")

		self.taskListView:removeAllChildren()
		
		local sortedTasks = {}
		for i, v in ipairs(taskArray) do
			-- print("carnival task:", v)
			local t = self.model:getTask(checknumber(v))
			if not t then --没开始的任务，读配置
				local conf = GD:queryTaskById(checknumber(v))
				if conf then
					t = Task.new()
					t.conf = conf
					t.taskProgress = {{Num=0, NeedNum=checknumber(conf.condition1Par2)}}
				end
			end
			if t then
				t.carnivalIndex = i
				table.insert(sortedTasks, t)
			end
		end 

		table.sort(sortedTasks, function(a, b)
			if a:isRewarded() then
				if b:isRewarded() then
					return a.carnivalIndex < b.carnivalIndex
				else
					return false
				end
			elseif a:isFinished() then
				if b:isFinished() then
					return a.carnivalIndex < b.carnivalIndex
				else
					return true
				end
			else
				if b:isRewarded() then
					return true
				elseif b:isFinished() then
					return false
				else
					return a.carnivalIndex < b.carnivalIndex
				end
			end
		end)

		for i, v in ipairs(sortedTasks) do
			self.taskListView:pushBackCustomItem(self:getListItem(v, checknumber(v.conf.quality)))
		end		
	end
end

function RewardCarnivalPanel:refreshProgressRewards()
	local finishedCount = 0
	local totalCount = 0
	local partValues = {}
	for i, v in ipairs(self.model.sortedProgresses) do 
		local cfg = self.model.sortedProgresses[i]
		if cfg then
			totalCount = math.max(totalCount, checknumber(cfg.progressValue))
			table.insert(partValues, checknumber(cfg.progressValue))
			local finished = self.model.currentProgressValue >= checknumber(cfg.progressValue)
			local rewarded = finished and not ( self.model:hasRewarded(checknumber(cfg.ID)))			

			local data = {config = cfg, count = cfg.progressValue, rewardID=cfg.rewardID, finished = finished, rewarded=rewarded}
			if self.rewards[i] then
				if finished then
					finishedCount = finishedCount + 1
				end
				self.rewards[i]:setData(data)
				self.rewards[i]:setVisible(true)
			end
		end
	end 
	-- finishedCount=2
	self:findChild("Panel/Panel_bom/num"):setString(tostring(self.model.currentProgressValue))
	
	local percents = {25, 40, 60, 80, 100}
	if totalCount == 0 then totalCount = 1 end
	local partvalue = math.max(checknumber(partValues[finishedCount+1]) - checknumber(partValues[finishedCount]), 1)
	local partpct = (self.model.currentProgressValue - checknumber(partValues[finishedCount]))/partvalue * 15
	self:findChild("Panel/Panel_bom/bar/LoadingBar"):setPercent(checknumber(percents[finishedCount]) + partpct)
end

function RewardCarnivalPanel:getListItem(t, index)
	-- dump(t, "taskinfo:")
	local r = cc.CSLoader:createNode(Res.RewardCarnivalListNode)
	r:setContentSize(r:findChild("Panel"):getContentSize())

	local tlt = r:findChild("Panel/tlt")
	tlt:setString(L(t.conf.name))
	local content = r:findChild("Panel/Text")
	content:setString(L(t.conf.target))

	--local num = r:findChild("Panel/num")
	--num:setString(tostring(index))

	local bar = r:findChild("Panel/bar")
	local btn = r:findChild("Panel/btn_receive")
	local over = r:findChild("Panel/img_over")

	bar:hide()
	btn:hide()
	over:hide()

	btn:addClickEventListener(function(sender)
		if t:isFinished() and not t:isRewarded() then
			app.session:request("pb_activity.C2S_GetTaskActivityReward",{taskId = tostring(t.id)},function(msg)
				if msg and msg.ok and cc.isDead(self) == false then
					self.model:newReqInfo()
				end 
			end)
		end		
	end)

	local icons = {}
	for i = 1, 4 do 
		table.insert(icons, IconRender.create(r:findChild("Panel/icon_"..tostring(i))))
		icons[i]:hide()
	end

	local rewards = t:getRewards()

	for i, v in ipairs(rewards) do
		local drops = UD:parseLootToBagItem(v)
		if drops then
			local d = drops
			icons[i]:setTipEnable( true )
			icons[i]:setData(d)
			icons[i]:show()
		end
	end

	local function setListHighLight(highlight)
		local bgh = r:findChild("Panel/Panel_bg/bg_1")
		local bgn = r:findChild("Panel/Panel_bg/bg_2")
		bgh:hide()
		bgn:hide()

		if highlight then
			bgh:show()
		else
			bgn:show()
			--r:findChild("Panel/num_mask"):show()
			tlt:setTextColor(cc.c3b(178, 178, 178))
		end
	end

	if t:isFinished() then
		btn:show()
		setListHighLight(false)
	elseif t:isRewarded() then
		over:show()
		setListHighLight(true)
	else
		bar:show()
		local p = t.taskProgress[1]
		r:findChild("Panel/bar/num"):setString(L("lua_code_text_353")..tostring(p.Num).."/"..tostring(p.NeedNum))
		r:findChild("Panel/bar/LoadingBar"):setPercent(p.Num/p.NeedNum * 100)
		setListHighLight(false)
	end
	
	return r 
end

function RewardCarnivalPanel:refresh()
	if self._data then
	end
	if self.model.beginTimeStamp == nil then
		return
	end
	local curDay = self.currentDay or self.model:getCurDay()
	self.dayBtns[curDay].select()
	self:refreshList(curDay)
	self:refreshTimeString()
	self:refreshProgressRewards()
	self:refreshDayRedPoint()
end

function RewardCarnivalPanel:onBtnClick(cb)
	self._onBtnClick = cb
end

function RewardCarnivalPanel:onOperate()
end

return RewardCarnivalPanel